package cn.xo68.boot.auth.client.configuration;


import cn.xo68.boot.auth.client.properties.AuthProviderProperties;
import cn.xo68.boot.auth.core.properties.OAuthResourceProperties;
import cn.xo68.core.entity.JsonResponsEntity;
import cn.xo68.core.util.JsonUtil;
import com.fasterxml.jackson.databind.JavaType;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.stereotype.Service;

/**
 * 认证 客户端
 * @author wuxie
 * @date 2019-1-4
 */
@Service
public class SecurityClient {

    private final OAuthResourceProperties oAuthResourceProperties;
    private final AuthProviderProperties authProviderProperties;
    private final JsonUtil jsonUtil;

    public SecurityClient(OAuthResourceProperties oAuthResourceProperties, AuthProviderProperties authProviderProperties, JsonUtil jsonUtil) {
        this.oAuthResourceProperties = oAuthResourceProperties;
        this.authProviderProperties = authProviderProperties;
        this.jsonUtil = jsonUtil;
    }

    /**
     * 请求服务端接口并序列化为java对象
     * @param url
     * @param accessToken
     * @param requestMethod
     * @param dataJavaType
     * @param <T>
     * @return
     * @throws OAuthSystemException
     * @throws OAuthProblemException
     */
    public <T> T getResource(String url, String accessToken, String requestMethod, JavaType dataJavaType) throws OAuthSystemException, OAuthProblemException {
        String resultStr = null;
        OAuthClient oAuthClient =new OAuthClient(new URLConnectionClient());

        if(url.indexOf(OAuth.OAUTH_CLIENT_ID)==-1){
            if(url.indexOf("?")==-1){
                url+="?";
            }
            url+= OAuth.OAUTH_CLIENT_ID+"="+oAuthResourceProperties.getClientId();
        }

        OAuthClientRequest rsRequest = new OAuthBearerClientRequest(url).setAccessToken(accessToken).buildQueryMessage();
        //rsRequest.addHeader(OAuth.OAUTH_CLIENT_ID, oAuthResourceProperties.getClientId());
        OAuthResourceResponse resourceResponse = oAuthClient.resource(rsRequest, requestMethod, OAuthResourceResponse.class);
        boolean isSuccess = resourceResponse.getResponseCode() == 200;
        if(isSuccess) {
            resultStr = resourceResponse.getBody();
            T result = jsonUtil.parse(resultStr,  dataJavaType);
            return result;
        } else {
            String body = resourceResponse.getBody();
            throw new AuthenticationException(body);
        }
    }
}
